
import { Button, Component, find, Label, Node, RichText } from 'cc';
import { tyqSDK } from '../Managers/TyqSDK';
import { tyqLayerManager } from '../Managers/TyqLayerManager';

export class TyqBaseLayer extends Component {

    public obj: any = {};
    public cb: Function;
    public layerName: string = "DefaultLayer";

    // {路径:节点对象}
    public pathNodeObj: Map<string, Node> = new Map();

    onLoad() {
        this.addButtonListener(this.node);
        this.addPathNode(this.node, "");
    }

    addPathNode(node: Node, path: string) {
        if (node != this.node) {
            this.pathNodeObj.set(path, node);
        }
        if (path) {
            path += "/";
        }
        let chs = node.children;
        for (let i = 0, len = chs.length; i < len; i++) {
            let pNode = chs[i];
            this.addPathNode(pNode, path + pNode.name);
        }
    }

    getNodeByPath(path: string) {
        let node = this.pathNodeObj.get(path);
        if (node) {
            return node;
        }

        node = find(path, this.node);
        if (node) {
            this.pathNodeObj.set(path, node);
            return node;
        }

        return null;
    }

    addButtonListener(node: Node) {
        if (node.getComponent(Button)) {
            node.on("click", this.preOnButtonClick, this);
        }

        let chs = node.children;
        for (let i = 0, max = chs.length; i < max; i++) {
            let ch = chs[i];
            this.addButtonListener(ch);
        }

    };

    preOnButtonClick(btn: any) {
        let node = btn.node;
        let name = node.name;
        tyqSDK.log(this.layerName + " onButtonClick " + name);

        this.onButtonClick(node, node.name);

    }

    onButtonClick(node: Node, name: String) {

    }

    openLayer(layerName: string, data?: any, cb?: Function) {
        tyqLayerManager.openLayer(layerName, data, cb);
    }

    closeLayer() {
        tyqLayerManager.closeLayer(this);
    }

    setString(node: Node, info: any) {
        info = info + "";
        let label = node.getComponent(Label);
        if (label) {
            label.string = info;
            return;
        }

        let rich = node.getComponent(RichText);
        if (rich) {
            rich.string = info;
            return;
        }
    }
}

